package com.longrise.android.loaddata;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;

import com.longrise.LEAP.Base.IO.JSONSerializer;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.util.PreferenceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class LoadFileRunnable implements Runnable {

	private static final String TAG = "LoadFileRunnable";
    private String url;
	private String localpath;
	private OnDownLoadFileListener onDownLoadFileListener;
	private boolean mIscopy = true;
	private boolean nowDownLoad = false;
	private String userflag;
	private EntityBean loadDownInfo = null;
	private String catchPath = "http://download.yxybb.com/bbvideo/web/d1/d20/d20/f3-web.mp4";
	private SharedPreferences sp;
	private Handler handler = null;
	private OnStopTaskListener onStopTaskListener;

	
	public  LoadFileRunnable(String url,String localpath,OnDownLoadFileListener onDownLoadFileListener)
	{
		this.url = url;
		this.localpath = localpath;
		this.onDownLoadFileListener = onDownLoadFileListener;
		sp = LoadDataManager.getInstance().getContext().getSharedPreferences(LoadDataManager.SP_NAME,
				LoadDataManager.getInstance().getContext().MODE_PRIVATE);
		handler = new Handler();
	}

	public void setIscopy(boolean iscopy){
		this.mIscopy = iscopy;
	}

	public String getUrl() {
		return url;
	}
	public String getLocalpath() {
		return localpath;
	}
	public void setOnDownLoadFileListener(OnDownLoadFileListener onDownLoadFileListener)
	{
		this.onDownLoadFileListener = onDownLoadFileListener;
	}

	public void setNowDownLoad(boolean b)
	{
		this.nowDownLoad = b;
	}

	public boolean getNowDownLoad()
	{
		return this.nowDownLoad;
	}

	public void setUserflag(String userflag)
	{
		this.userflag = userflag;
	}

	public void setCatchPath(String catchPath)
	{
		this.catchPath = catchPath;
	}

	long totalLength = 0;
	long downedFileLength=0;
	int progress = -1;
	@Override
	public void run() 
	{
		InputStream inputStream = null;
		HttpURLConnection connection = null;
		RandomAccessFile randomAccessFile = null;
		try 
		{
			String value = PreferenceUtils.getPrefString(LoadDataManager.SP_NAME, Context.MODE_PRIVATE, LoadDataManager.getInstance().getContext(),
					userflag + "_mark_" + url, null);
			if(null != sp)
			{
				value = sp.getString(userflag + "_mark_" + url,null);
			}

			if(null != value)
			{
				this.loadDownInfo = (EntityBean) JSONSerializer.getInstance().DeSerialize(value,EntityBean.class);
			}

			if(null == this.loadDownInfo)
			{
				loadDownInfo = new EntityBean();
			}
			Log.e(TAG,"URL;;;;;:"+Environment.getExternalStorageDirectory().toString());
			String fileDir = Environment.getExternalStorageDirectory().toString()+ "/" +
					LoadDataManager.getInstance().getContext().getApplicationInfo().packageName
					+ "/Video/" +  userflag ;

			//创建目录
			if(!new File(fileDir).exists())
			{
				boolean b = new File(fileDir).mkdirs();
				if(!b)
				{
					if(handler != null)
					{
						handler.post(new Runnable() {
							@Override
							public void run() {

								if(onDownLoadFileListener != null)
								{
									onDownLoadFileListener.downLoadFailure(LoadFileRunnable.this);
								}
								return;
							}
						});
					}

				}
			}

			localpath = fileDir +"/"+catchPath;
            Log.d(TAG,"localpath:"+localpath);
			//判读文件是否存在
			File file = new File(localpath);
			if(file.exists())
			{
			   downedFileLength = getFileSize(file);
			   Log.d(TAG, "本地文件长度："+downedFileLength);
			}
			else
			{
				progress = -1;
				downedFileLength = 0 ;
				File parentFile = file.getParentFile();
				if(!parentFile.exists()){
					boolean mkdirs = parentFile.mkdirs();
					if(!mkdirs){
						if(handler != null)
						{
							handler.post(new Runnable() {
								@Override
								public void run() {

									if(onDownLoadFileListener != null)
									{
										onDownLoadFileListener.downLoadFailure(LoadFileRunnable.this);
									}
									return;
								}
							});
						}
					}
				}

				//判断是否创建成功
 	            boolean createFileSuccess = file.createNewFile();
	            if(!createFileSuccess)
	            {
					if(handler != null)
					{
						handler.post(new Runnable() {
							@Override
							public void run() {

								if(onDownLoadFileListener != null)
								{
									onDownLoadFileListener.downLoadFailure(LoadFileRunnable.this);
								}
								return;
							}
						});
					}
	            }

			}

			//保存本地路径
			loadDownInfo.set("localpath", localpath);

			URL url=new URL(this.url);
            connection=(HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(50000);
            connection.setReadTimeout(10000);

            randomAccessFile = new RandomAccessFile(file, "rwd");
            randomAccessFile.seek(downedFileLength);
            connection.setRequestProperty("Range", "bytes=" + downedFileLength + "-");

            //输入流
            inputStream=connection.getInputStream();
			if(totalLength==0){
				totalLength=connection.getContentLength();
				totalLength = totalLength + downedFileLength;
			}

			if(handler != null)
			{
				handler.post(new Runnable() {
					@Override
					public void run() {

						if(onDownLoadFileListener != null)
						{
							//Log.e("文件长度----------->", downedFileLength+"");
							//onDownLoadFileListener.downLoadStar(totalLength/ 1024 / 1024.0f);
							onDownLoadFileListener.downLoadStar(totalLength);
						}
					}
				});
			}

            byte[] buffer = new byte[1024 * 4];
            int length = -1;

            while((length = inputStream.read(buffer)) != -1 && nowDownLoad)
			{
				randomAccessFile.write(buffer, 0, length);
				downedFileLength += length;
                Log.d(TAG,"downedFileLength::"+downedFileLength);
				int nowProgress = (int)((100 * downedFileLength)/totalLength);
				if(nowProgress > progress)
				{
					progress = nowProgress;
					//设置下载状态
					loadDownInfo.set("downLoadStatus","progress");
					loadDownInfo.set("progress",progress + "");
					loadDownInfo.set("downedFileLength",downedFileLength+"");
					loadDownInfo.set("totalLength",totalLength+"");

					if(null != sp)
					{
						sp.edit().putString(userflag + "_mark_" + url, JSONSerializer.getInstance().Serialize(loadDownInfo)).commit();
					}

					handler.post(new Runnable() {
						@Override
						public void run() {

							if(onDownLoadFileListener != null)
							{
								//Log.e("文件长度----------->", downedFileLength+"");
								//onDownLoadFileListener.downLoadProgerss(progress,downedFileLength/ 1024 / 1024.0f,totalLength/ 1024 / 1024.0f);
								onDownLoadFileListener.downLoadProgerss(progress,downedFileLength,totalLength);
								Log.d(TAG,"totalLength000:"+totalLength);
							}
						}
					});
				}
            }

			if(nowDownLoad)
			{
				if(totalLength!=0 && totalLength==downedFileLength){  //下载成功
				//设置下载状态
				loadDownInfo.set("downLoadStatus","success");
				if(null != sp)
				{
					sp.edit().putString(userflag + "_mark_" + url, JSONSerializer.getInstance().Serialize(loadDownInfo)).commit();
				}

				//成功后设置停止
				nowDownLoad = false;
				if(handler != null)
				{
					handler.post(new Runnable() {
						@Override
						public void run() {

							if(onDownLoadFileListener != null)
							{
								onDownLoadFileListener.downLoadSuccess(LoadFileRunnable.this);
							}
						}
					});
				}

				}else{  //网络原因导致下载失败

					//设置下载状态
					loadDownInfo.set("downLoadStatus","failure");
					nowDownLoad = false;
					if(null != sp)
					{
						sp.edit().putString(userflag + "_mark_" + url, JSONSerializer.getInstance().Serialize(loadDownInfo)).commit();
					}

					if(handler != null)
					{
						handler.post(new Runnable() {
							@Override
							public void run() {

								if (onDownLoadFileListener != null) {
									onDownLoadFileListener.downLoadFailure(LoadFileRunnable.this);
								}
							}
						});
					}

				}
			}
			else
			{
				if(handler != null)
				{
					handler.post(new Runnable() {
						@Override
						public void run() {

							if(null != onStopTaskListener)
							{
								onStopTaskListener.onStopTask(LoadFileRunnable.this,true);
							}
						}
					});
				}

			}


        }
		catch (Exception e)
        {
			Log.d(TAG,"EXCEPTION::"+e.toString());
            e.printStackTrace();
			//设置下载状态
			loadDownInfo.set("downLoadStatus","failure");
			nowDownLoad = false;
			if(null != sp)
			{
				sp.edit().putString(userflag + "_mark_" + url, JSONSerializer.getInstance().Serialize(loadDownInfo)).commit();
			}

			if(handler != null)
			{
				handler.post(new Runnable() {
					@Override
					public void run() {

						if (onDownLoadFileListener != null) {
							onDownLoadFileListener.downLoadFailure(LoadFileRunnable.this);
						}
					}
				});
			}

			if(handler != null)
			{
				handler.post(new Runnable() {
					@Override
					public void run() {

						if(null != onStopTaskListener)
						{
							onStopTaskListener.onStopTask(LoadFileRunnable.this, true);
						}
					}
				});
			}

        } 
		finally
		{
			try 
			{
				if(connection != null)
                {
					connection.disconnect();
                }
				if(null != inputStream)
				{
					inputStream.close();
				}
				if(null!=randomAccessFile){
				    randomAccessFile.close();
				}
				
			} 
			catch (Exception e2) 
			{
				e2.printStackTrace();
			}
			
		}
	}
	
	/**
	 * 获取文件名
	 * @param localPath
	 * @return
	 */
	private String getFileName(String localPath){
	    String fileName = null;
	    if(localPath!=null){
	        String name = localPath.toLowerCase();
	        if(localpath.contains("/")){
	          fileName  = localpath.substring(localpath.lastIndexOf("/")+1, localpath.length());
	        }
	    }
        return fileName;
	}
	
	/**
     * 获取文件的下载类型
     * @return
     */
    private String getType(String fileName)
    {
        String type = null;
        if(fileName != null)
        {
            String name = fileName.toLowerCase();
            if (name.contains(".")) 
            {
                type = name.substring(name.lastIndexOf("."), name.length());
            }
            
        }
        return type;
    }
    
    /**  
     *  复制单个文件  
     *  @param  oldPath  String  原文件路径  如：c:/fqf.txt  
     *  @param  newPath  String  复制后路径  如：f:/fqf.txt  
     *  @return  boolean  
     */  
    private boolean  copyFile(String  oldPath,  String  newPath)  {
        boolean iscopy = false;
        InputStream  inStream  =  null;  
        FileOutputStream  fs  =  null;
        try  { 
        		//判断新的文件是否存在
        		File newFile = new File(newPath);
        		if(newFile.exists())
        		{
        			//存在就删除再创建
        			boolean delBool = newFile.delete();
        			if(!delBool)
        			{
        				boolean creBool = newFile.createNewFile();
        				if(!creBool)
        				{
        					return false;
        				}
        			}
        		}
        		else
        		{
        			File parentFile = newFile.getParentFile();
        			if(!parentFile.exists())
        			{
        				boolean createParentBool = parentFile.mkdirs();
        				if(!createParentBool)
        				{
        					return false;
        				}
        			}
        			parentFile = null;
        			
        			boolean creBool = newFile.createNewFile();
    				if(!creBool)
    				{
    					return false;
    				}
			}
        		
            int  byteread  =  0;  
            File  oldfile  =  new  File(oldPath);  
            if  (oldfile.exists())
            {
            		//文件存在时  
                inStream  =  new  FileInputStream(oldPath); //读入原文件  
                fs  =  new  FileOutputStream(newPath);
                byte[]  buffer  =  new  byte[1024];  
                while  ((byteread  =  inStream.read(buffer))  !=  -1)  {  
                    fs.write(buffer,  0,  byteread);  
                }
                iscopy = true;
                //删除缓存
                oldfile.delete();
            }  
        }  
        catch  (Exception  e)  {  
            e.printStackTrace();  
        }finally{
            try {
                if(inStream != null){
                    inStream.close();
                } 
            } catch (IOException e) {
                e.printStackTrace();
            } 
            try {
                if(fs != null){
                    fs.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return iscopy;
    }

	/* 获取指定文件大小
	*
    * @param f
	* @return
    * @throws Exception
	*/
	private long getFileSize(File file) throws Exception
	{
		long size = 0;
		if (file.exists())
		{
			FileInputStream fis = null;
			fis = new FileInputStream(file);
			size = fis.available();
		}
		return size;
	}

	/**
	 * 停止任务
	 * @param nowDownLoad
	 * @param onStopTaskListener
     */
	public void stopTask(boolean nowDownLoad,OnStopTaskListener onStopTaskListener)
	{
		//注意这个赋值顺序，不能改变
		this.onStopTaskListener = onStopTaskListener;
		this.nowDownLoad = nowDownLoad;
	}


}
